<?php
/**
 * User: 五哥派
 * Date: 2024/7/1
 * Tel(同WX): 17335592719
 */
namespace app\admin\controller\dealer;

use app\admin\controller\Base;
use app\admin\model\dealer\Apply as ApplyModel;
use app\admin\model\dealer\User as UserModel;
use think\Db;
use think\Exception;

class Apply extends Base{

    protected $model;
    public function __construct(ApplyModel $model){
        parent::__construct();
        $this->model = $model;
    }

    public function lst(){
        return $this->fetch();
    }
    public function lstajax(){
        $list = $this->model->getList();
        $result = $list->toArray();
        return showLayui($result['total'], $result['data']);
    }

    public function del(){
        $id = input('id');
        //删除
        $res = $this->model->delDataByID($id);
        if($res){
            return success('删除成功!');
        }else{
            return error('删除失败!');
        }
    }

    public function audit(){
        if(request()->isPost()){
            $data = request()->param();
            Db::startTrans();
            try {
                if ($data['apply_status'] == 30 && empty($data['reject_reason'])) {
                    //return error('请填写驳回原因!');
                    throw new Exception('请填写驳回原因');
                }

                // 新增分销商用户
                if ($data['apply_status'] == 20) {
                    $applyId = $data['id'];
                    $apply = ApplyModel::detail($applyId);
                    $mUserModel = new UserModel();//分销用户
                    $userInfo = [
                        'name' => $apply['name'],
                        'mobile' => $apply['mobile'],
                        'user_id' => $apply['user_id'],
                        'referee_id' => $apply['referee_id']
                    ];
                    $mUserModel->saveData($userInfo, false);
                }
                $this->model->saveData($data,true);
                Db::commit();
                return success('保存成功!');
            }catch (Exception $e){
                Db::rollback();
                return error($e->getMessage());
            }

        }

        $id = $this->request->param('id');
        $data = $this->model->findDataByID($id);
        $this->assign('data',$data);
        return $this->fetch();
    }

}

